package com.leyou.auth.task;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.entity.AppInfo;
import com.leyou.auth.mapper.ApplicationInfoMapper;
import com.leyou.common.auth.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 定时获取token，保存token
 *
 * @author 虎哥
 */
@Slf4j
@Component
public class PrivilegeTokenHolder {

    @Autowired
    private JwtProperties prop;

    @Autowired
    private ApplicationInfoMapper infoMapper;
    private String token;


    /**
     * token刷新间隔
     */
    private static final long TOKEN_REFRESH_INTERVAL = 86400000L;

    @Scheduled(fixedDelay = TOKEN_REFRESH_INTERVAL)
    public void loadToken() throws InterruptedException {
        try {
				// 查询权限服务列表
                List<Long> targetIdList = infoMapper.queryTargetIdList(prop.getApp().getId());
                // 封装载荷
                AppInfo appInfo = new AppInfo();
                appInfo.setId(prop.getApp().getId());
                appInfo.setServiceName(prop.getApp().getSecret());
                appInfo.setTargetList(targetIdList);
            this.token = JwtUtils.generateTokenExpireInMinutes(appInfo, prop.getPrivateKey(), prop.getApp().getExpire());
            log.info("【网关】定时获取token成功,token:[{}]",token);
        } catch (Exception e) {
            log.info("【网关】定时获取token失败,原因:{}",e.getMessage(),e);
        }
    }
    public String getToken() {
        return token;
    }
}